package com.lipiao.traveltreasure.controller.restaurant;

import com.lipiao.traveltreasure.bean.restaurantBean.Food;
import com.lipiao.traveltreasure.service.restaurant.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 餐厅管理 控制器
 * 1.添加菜品信息 菜名 价格 彩屏详细 图片
 * 2.
 */
@Api(tags = "点餐小程序-管理员")
@Controller
@RequestMapping(value = "/restaurantApi/admin")
public class AdminController {

    static String fileLocation = "/restaurantRes/";//图片资源访问路径
    //存储预返回页面的结果对象
    private Map<String, Object> result = new HashMap<>();
    //注入业务对象
    @Resource
    private AdminService adminService;


    /**
     * 1.添加菜品信息(菜名 价格 彩屏详细 菜对应的图片 类别)
     * @param name
     * @param prices
     * @param description
     * @param pictureFile
     * @param type
     * @param request
     * @return
     */
    @ApiOperation(value = "添加菜品信息", notes = "注意事项：POST请求，参数String name菜品名称, " +
            "double prices菜品价格, String description菜品描述, Part pictureFile菜品图片文件, int type菜品类别(主食是0，小菜是1，饮料是2)")
    @PostMapping("/addFood")
    @ResponseBody
    public Map<String, Object> addFood(String name, double prices, String description, Part pictureFile,
                                       int type, HttpServletRequest request) {
        //获取提交文件名称
        String filename = pictureFile.getSubmittedFileName();

        //定义上传文件存放的路径
        String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
        System.out.println(path);
        //返回保存的url，根据url可以进行文件查看或者下载
        String filePath = request.getScheme() + "://" + request.getServerName()
                //+ ":" + request.getServerPort() //端口 https443端口无需添加
                + fileLocation + filename;

        String pictureFileURL = filePath;//根路径+文件名

        String id = UUID.randomUUID() + "";//使用UUID随机生成一个菜品Id
        adminService.addFood(new Food(name, prices, description, pictureFileURL, id, type));

        //写入文件
        try {
            pictureFile.write(filename);
            result.put("Result", "添加菜品信息成功");
        } catch (IOException e) {
            e.printStackTrace();
            result.put("Result", "添加菜品信息失败");
        }
        return result;
    }


}
